package model

import (
	"gorm.io/gorm/clause"
	"server/common"
)

// api接口测试model
type Restful struct {
	Model
	URL  string `gorm:"column:url;not null;type:varchar(300);" json:"url"`
	Name string `gorm:"column:name;not null;type:varchar(32)" json:"name"`

	UrlParam map[string]string `gorm:"-"`

	METHOD     string `gorm:"column:method;not null;type:enum('get','post','delete','put','head');default:'get'" json:"method"`
	HOST       string `gorm:"column:host;type:varchar(300);" json:"host"`
	RESPONSE   string `gorm:"column:response;type:longtext" json:"response"`
	STATUSCODE int    `gorm:"column:status_code;type:int;default:200" json:"statu_scode"`
	Body       string `gorm:"column:body;type:longtext;" json:"body"`

	OwnerID int `json:"owner_id"`
	Owner   Owner

	FatherID int `gorm:"column:father" json:"father"`
	Father   RestfulMeau

	RestfulMeauID int `gorm:"comuln:restful_meau_id;" json:"restful_meau_id"`
}

func (m *Restful) TableName() string {
	return "restful"
}

func (m *Restful) Info() error {
	if err := common.DB.Omit(clause.Associations).Where("id = ?", m.ID).Find(&m); err != nil {
		return err.Error
	}
	return nil
}

func (m *Restful) List() ([]Restful, int64) {
	tasks := []Restful{}
	var count int64
	if err := common.DB.Preload(clause.Associations).Order("id desc").Find(&tasks).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
		return tasks, count
	}
	return tasks, count
}

func (m *Restful) Create() error {
	if err := common.DB.Debug().Create(&m).Error; err != nil {
		return err
	}
	return nil
}

func (m *Restful) Update() error {
	if err := common.DB.Omit(clause.Associations).Where("name = ?", m.Name).Updates(&m).Error; err != nil {
		return err
	}
	return nil
}

func (m *Restful) Delete() error {
	if err := common.DB.Where("name = ?", m.Name).Delete(&m).Error; err != nil {
		return err
	}
	return nil
}
